import heapq
tasks = [(3, "处理普通任务"), (1, "处理紧急任务"), (2, "处理重要任务")]
heapq.heapify(tasks)
while tasks:
    priority, task = heapq.heappop(tasks)
    print(f"执行任务：{task}，优先级：{priority}")  # 输出顺序：紧急→重要→普通 [2,4](@ref)

data = [10, 2, 5, 8, 3, 9, 6]
top3 = heapq.nlargest(3, data)  # 输出 [10, 9, 8]
bottom2 = heapq.nsmallest(2, data)  # 输出 [2, 3] [3,7](@ref)


"""
三、堆排序
利用堆结构实现高效的排序算法，时间复杂度为 O(n log n)：
"""
def heap_sort(data):
    heapq.heapify(data)
    heapq.heapify(data)
    return [heapq.heappop(data) for _ in range(len(data))]

sorted_data = heap_sort([5, 3, 7, 2, 1, 8])
print(sorted_data)# 输出 [1, 2, 3, 5, 7, 8] [6,7](@ref)


sorted1 = [1, 4, 7]
sorted2 = [2, 5, 8]
merged = heapq.merge(sorted1, sorted2)  # 返回迭代器 [1, 2, 4, 5, 7, 8] [6,7](@ref)
print(list(merged))


import heapq

# 元组结构：(主优先级, 次优先级, 任务描述)
tasks = []
heapq.heappush(tasks, (3, 2, "处理普通日志"))
heapq.heappush(tasks, (1, 5, "修复服务器崩溃"))
heapq.heappush(tasks, (1, 3, "响应客户紧急请求"))

# 弹出顺序：主优先级 > 次优先级
while tasks:
    print(heapq.heappop(tasks))  # 依次输出 (1,3), (1,5), (3,2)


import time

events = []
heapq.heappush(events, (time.time() + 3600, "定时备份"))  # 1小时后执行
heapq.heappush(events, (time.time() + 300, "5分钟后重启"))
print(events)